#include <singleton_woker_queue_thread.h>

SingletonWorkerQueueThread::SingletonWorkerQueueThread()
{
    worker_thread_ = std::make_unique<std::thread>( &SingletonWorkerQueueThread::work_loop, this );
}

SingletonWorkerQueueThread::~SingletonWorkerQueueThread()
{
    stop();
}

void SingletonWorkerQueueThread::work_loop()
{
    //using namespace std::chrono_literals;
    Task task;

    while(running_)
    {
        {
            std::unique_lock<std::mutex> lg{ mutex_ };
            while (task_queue_.empty() && running_)
                cv_.wait(lg);
        }

        if (!task_queue_.empty())
        {// there is a task available
            std::unique_lock<std::mutex> lg{ mutex_ };
            task = std::move(task_queue_.front());
            task_queue_.pop();
            task();
        }
    }

}

void SingletonWorkerQueueThread::stop()
{
    running_ = false;
    cv_.notify_all();

    if(worker_thread_->joinable() ) {
        worker_thread_->join();
    }
}
